﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.Windows.Resources;
using System.IO;

namespace myChannel9
{
    public partial class Control_Tags : UserControl
    {
        public event EventHandler goToTags;

        public Control_Tags()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            loadAllTags();
        }

        private void lboTags_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            TagObject tag = lboTags.SelectedItem as TagObject;

            if (tag != null)
            {
                if (tag.BoxSize == 0)
                {
                    if (IsolatedStorageSettings.ApplicationSettings.Contains("Tag"))
                        IsolatedStorageSettings.ApplicationSettings["Tag"] = tag;
                    else
                        IsolatedStorageSettings.ApplicationSettings.Add("Tag", tag);

                    goToTags(tag, new EventArgs());
                    lboTags.SelectedIndex = -1;
                }
            }
        }

        private void loadAllTags()
        {
            try
            {
                List<TagObject> tagList = new List<TagObject>();

                if (IsolatedStorageSettings.ApplicationSettings.Contains("TagList"))
                {
                    tagList = IsolatedStorageSettings.ApplicationSettings["TagList"] as List<TagObject>;
                }
                else
                {
                    StreamResourceInfo res = Application.GetResourceStream(new Uri("Resources/Tags.txt", UriKind.Relative));
                    StreamReader st = new StreamReader(res.Stream);
                    string line = "";

                    while ((line = st.ReadLine()) != null)
                    {
                        if (line.Substring(0, 1) == "*")
                        {
                            tagList.Add(new TagObject { BoxChar = line.Substring(1, 1), BoxSize = 70 });
                        }
                        else
                        {
                            tagList.Add(new TagObject { Tag = line });
                        }
                    }

                    IsolatedStorageSettings.ApplicationSettings.Add("TagList", tagList);
                }

                lboTags.ItemsSource = tagList;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

    }
}
